package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.*;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    public static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.upload-path}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private FollowService followService;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @Value("${qiniu.bucket.header.name}")
    private String headerBucketName;

    @Value("${qiniu.bucket.header.url}")
    private String headerBucketUrl;

    @RequestMapping(value = "/setting", method = RequestMethod.GET)
    @LoginRequired
    public String getSettingPage(Model model) {
        // 生成上传头像图片的名称
        String filename = CommunityUtil.generateUUID();
        // 设置云服务器的响应信息
        StringMap policy = new StringMap();
        policy.put("returnBody", CommunityUtil.getJSONString(0));
        // 生成头像的上传凭证
        Auth auth = Auth.create(accessKey, secretKey);
        String uploadToken = auth.uploadToken(headerBucketName, filename, 3600, policy);

        model.addAttribute("uploadToken", uploadToken);
        model.addAttribute("filename", filename);

        return "/site/setting";
    }

    // 更新头像的路径
    @RequestMapping(path = "/header/url", method = RequestMethod.POST)
    @ResponseBody
    public String updateHeaderUrl(String filename) {
        if (StringUtils.isBlank(filename)) {
            return CommunityUtil.getJSONString(1, "文件名不能为空!");
        }

        String url = headerBucketUrl + "/" + filename;
        userService.updateHeader(hostHolder.getUser().getId(), url);

        return CommunityUtil.getJSONString(0);
    }

    // 废弃
    @RequestMapping(value = "/upload-header", method = RequestMethod.POST)
    @LoginRequired
    public String uploadHeader(MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            model.addAttribute("error", "您还没有选择图片!");
            return "/site/setting";
        }
        String filename = headerImage.getOriginalFilename();
        if (filename == null) {
            model.addAttribute("error", "您还没有选择图片!");
            return "/site/setting";
        }
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (suffix.isEmpty() || (!".png".equals(suffix) && !".jpg".equals(suffix) && !".jpeg".equals(suffix))) {
            model.addAttribute("error", "图片格式不正确!");
            return "/site/setting";
        }

        // 生成文件名
        User loginUser = hostHolder.getUser();
        filename = loginUser.getId() + suffix;
        // 确定文件的存放路径
        File dest = new File(uploadPath + "/" + filename);
        try {
            // 存储文件
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败: " + e.getMessage());
            throw new RuntimeException("上传文件失败,服务器发生异常!", e);
        }

        // 更新当前用户的头像的路径(web访问路径)
        // http://localhost:8080/community/user/header/xxx.png
        String headerUrl = domain + contextPath + "/user/header/" + filename;
        userService.updateHeader(loginUser.getId(), headerUrl);

        return "redirect:/user/setting";
    }

    // 废弃
    @RequestMapping(value = "/header/{filename}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("filename") String filename, HttpServletResponse response) {
        String format = filename.substring(filename.lastIndexOf('.') + 1);
        response.setContentType("image/" + format);
        try (
                FileInputStream fis = new FileInputStream(uploadPath + "/" + filename);
                ServletOutputStream os = response.getOutputStream()
        ) {
            byte[] buffer = new byte[1024];
            int readLen;
            while ((readLen = fis.read(buffer)) != -1) {
                os.write(buffer, 0, readLen);
            }
        } catch (IOException e) {
            logger.error("读取文件失败：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/update-password", method = RequestMethod.POST)
    @LoginRequired
    public String updatePassword(Model model, String oldPassword, String newPassword) {
        User loginUser = hostHolder.getUser();
        Map<String, Object> map = userService.updatePassword(loginUser.getId(), oldPassword, newPassword);
        if (map.isEmpty()) {
            // 修改密码成功
            return "redirect:/logout";
        } else {
            // 修改密码失败
            model.addAttribute("oldPasswordMsg", map.get("oldPasswordMsg"));
            model.addAttribute("newPasswordMsg", map.get("newPasswordMsg"));
            return "/site/setting";
        }
    }

    @RequestMapping(value = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(Model model, @PathVariable("userId") int userId) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在！");
        }
        model.addAttribute("user", user);

        // 该用户的获赞数
        model.addAttribute("userLikeCount", likeService.getUserLikeCount(userId));

        // 当前登录用户对该用户的关注状态
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {
            hasFollowed = followService.getFollowStatus(hostHolder.getUser().getId(), userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);

        // 该用户的关注数
        model.addAttribute("idolCount", followService.getIdolCount(userId));

        // 该用户的粉丝数
        model.addAttribute("followerCount", followService.getFollowerCount(userId));

        return "/site/profile";
    }

    @RequestMapping(value = "/my-post/{userId}", method = RequestMethod.GET)
    public String getMyPostPage(Model model, @PathVariable("userId") int userId, Page page) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在！");
        }
        model.addAttribute("user", user);

        // 当前用户的发帖总数
        int postCount = discussPostService.findDiscussPostRows(userId);
        model.addAttribute("postCount", postCount);

        // 分页信息
        page.setRows(postCount);
        page.setPath("/user/my-post/" + userId);

        List<DiscussPost> discussPostList = discussPostService.findDiscussPosts(userId, page.getLimit(), page.getOffset(), 0);
        List<Map<String, Object>> posts = new ArrayList<>();
        if (discussPostList != null) {
            for (DiscussPost discussPost : discussPostList) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", discussPost);
                map.put("likeCount", likeService.getEntityLikeCount(CommunityConstant.ENTITY_TYPE_POST, discussPost.getId()));
                posts.add(map);
            }
        }
        model.addAttribute("posts", posts);

        return "/site/my-post";
    }

    @RequestMapping(value = "/my-reply/{userId}", method = RequestMethod.GET)
    public String getMyReplyPage(Model model, @PathVariable("userId") int userId, Page page) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在！");
        }
        model.addAttribute("user", user);

        // 当前用户的回复总数
        int commentCount = commentService.findCommentRowsByUser(userId);
        model.addAttribute("commentCount", commentCount);

        // 分页信息
        page.setRows(commentCount);
        page.setPath("/user/my-reply/" + userId);

        List<Comment> commentList = commentService.findCommentsByUser(userId, page.getLimit(), page.getOffset());
        List<Map<String, Object>> comments = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                Map<String, Object> map = new HashMap<>();
                map.put("comment", comment);
                DiscussPost post = discussPostService.findDiscussPostById(comment.getEntityId());
                map.put("post", post);
                comments.add(map);
            }
        }
        model.addAttribute("comments", comments);

        return "/site/my-reply";
    }

}
